<?php
namespace App\Manager;

/**
 * 工具类
 */
class Util{
    const SALT = 'HelloDYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi';
    /**
     * 验证输入格式是否正确
     * @param Array $input
     * @return Bool 
     */
    public static function verifyInput($input)
    {
        $single_arr = ['type', 'data'];
        foreach ($single_arr as $v)
        {
            if (!isset($input[$v]))
            {
                return false;
            }
        }
        return true;
    }

    public static function verifyEnterData($data)
    {
        return true;
    }

    /**
     * @param param array
     * @param url string
     * @return result array
     */
    public static function post($url, $param)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 100);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        $str = curl_exec($ch);
        if($str === false)
        {
            throw new Exception(curl_error($ch));
        }
        //  释放cURL句柄
        curl_close($ch);
        var_dump($str);
        return json_decode($str, true);
    }

    /**
     * @param file string 本题文件路径
     * @param mimetype string 文件类型
     * @param postname string 上传文件名
     * @return resource
     */
    public static function create_file($file, $mimetype=null, $postname=null)
    {
        if (!file_exists($file))
        {
            throw new Exception("上传的文件不存在！");
        }
        return new CURLFile($file, $mimetype, $postname);
    }

    public static function uuid($prefix = '')
    {
        $chars = md5(uniqid(mt_rand(), true));
        $uuid  = substr($chars,0,8) . '-';
        $uuid .= substr($chars,8,4) . '-';
        $uuid .= substr($chars,12,4) . '-';
        $uuid .= substr($chars,16,4) . '-';
        $uuid .= substr($chars,20,12);
        return $prefix . $uuid;
    }

    public static function getfilecounts($dir){
        if (!file_exists($dir))
        {
            return 0;
        }
        $handle = opendir($dir);
        $i = 0;
        while(false !== $file=(readdir($handle))){
            if($file !== '.' && $file != '..' && is_file($dir . '/' . $file))
            {
                if (is_file($dir . '/' . $file) && $file != 'page_info.json')
                {
                    $i++;
                }
            }
        }
        closedir($handle);
        return $i;
    }
}